package org.jsola.hr.service.impl;

import org.jsola.core.Page;
import org.jsola.core.entity.BaseDO;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.IEmpContactsDAO;
import org.jsola.hr.dto.EmpContactsAddDTO;
import org.jsola.hr.dto.EmpContactsDTO;
import org.jsola.hr.dto.EmpContactsUpdateDTO;
import org.jsola.hr.entity.EmpContactsDO;
import org.jsola.hr.query.EmpContactsQuery;
import org.jsola.hr.service.IEmpContactsService;
import org.jsola.hr.vo.EmpContactsListVO;
import org.jsola.hr.vo.EmpContactsVO;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 员工联系人
 *
 * @author zhr
 */
@Service("hrEmpContactsServiceImpl")
public class EmpContactsServiceImpl implements IEmpContactsService {

    @Autowired
    private IEmpContactsDAO empContactsDAO;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public EmpContactsVO save(EmpContactsAddDTO empContactsAddDTO, TokenUser tokenUser) {
        // 转DO
        EmpContactsDO empContactsDO = empContactsAddDTO.to(EmpContactsDO.class);

        // 校验员工和公司
        checkEmpAndCompany(empContactsDO.getEmpId(), empContactsDO.getCompanyId(), tokenUser.getSiteId());

        // 保存
        empContactsDO = save(empContactsDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return empContactsDO.to(EmpContactsVO.class);
    }

    @Override
    public Integer onlySave(EmpContactsDO empContactsDO) {

        return empContactsDAO.insert(empContactsDO);
    }

    /**
     * 校验员工和公司
     *
     * @param empId     员工id
     * @param companyId 公司id
     * @param siteId    站点
     */
    private void checkEmpAndCompany(String empId, String companyId, String siteId) {
        ParamException.hasLength(empId, "员工id不能为空");
        ParamException.hasLength(companyId, "公司id不能为空");
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(EmpContactsUpdateDTO empContactsUpdateDTO, TokenUser tokenUser) {
        //转DO
        EmpContactsDO empContactsDO = empContactsUpdateDTO.to(EmpContactsDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(empContactsDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... empContactsIds) {
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) empContactsIds);
    }


    @Override
    public EmpContactsVO selectById(String empContactsId, String siteId) {
        EmpContactsDO empContactsDO = selectDOById(empContactsId, siteId);
        if (empContactsDO == null) {
            return null;
        }
        return empContactsDO.to(EmpContactsVO.class);
    }

    @Override
    public List<EmpContactsListVO> select(EmpContactsQuery empContactsQuery, String siteId) {
        List<EmpContactsDO> empContactsDOList = selectDO(empContactsQuery, siteId);
        if(CollectionUtils.isEmpty(empContactsDOList)) {
            return empContactsDOList == null ? null : new ArrayList<>();
        }
        return empContactsDOList.stream()
                .map(empContactsDO -> empContactsDO.to(EmpContactsListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(EmpContactsQuery empContactsQuery, String siteId) {
        Example example = buildExample(empContactsQuery,siteId);
        return empContactsDAO.selectCountByExample(example);
    }

    @Override
    public Page<EmpContactsListVO> selectPage(EmpContactsQuery empContactsQuery, String siteId) {
        Example example = buildExample(empContactsQuery,siteId);
        Page<EmpContactsDO> page = empContactsDAO.selectPageByExample(example,
                empContactsQuery.getPageNo(),
                empContactsQuery.getPageSize());

        return page.to(EmpContactsListVO.class);
    }

    @Override
    public EmpContactsDO selectDOById(String empContactsId, String siteId) {
        return listById(empContactsId, siteId);
    }

    @Override
    public List<EmpContactsDO> selectDO(EmpContactsQuery empContactsQuery, String siteId) {
        Example example = buildExample(empContactsQuery,siteId);
        return empContactsDAO.selectByExample(example);
    }


    /**
     * 根据查询参数，构建example

     * @param empContactsQuery 查询参数
     * @param siteId 所属站点id
     * @return example
     */
    private Example buildExample(EmpContactsQuery empContactsQuery, String siteId) {
        Example example = new Example(EmpContactsDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        if (empContactsQuery.getEmpId() != null) {
            example.and().andLike("empId", "%" + empContactsQuery.getEmpId() + "%");
        }
        if (empContactsQuery.getName() != null) {
            example.and().andLike("name", "%" + empContactsQuery.getName() + "%");
        }
        if (empContactsQuery.getRelation() != null) {
            example.and().andLike("relation", "%" + empContactsQuery.getRelation() + "%");
        }
        if (empContactsQuery.getPhone() != null) {
            example.and().andLike("phone", "%" + empContactsQuery.getPhone() + "%");
        }
        if (empContactsQuery.getAddress() != null) {
            example.and().andEqualTo("address", empContactsQuery.getAddress());
        }
        if (empContactsQuery.getWorkUnit() != null) {
            example.and().andLike("workUnit", "%" + empContactsQuery.getWorkUnit() + "%");
        }
        if (empContactsQuery.getPosition() != null) {
            example.and().andLike("position", "%" + empContactsQuery.getPosition() + "%");
        }
        if (empContactsQuery.getCompanyId() != null) {
            example.and().andEqualTo("companyId", empContactsQuery.getCompanyId());
        }
        if (empContactsQuery.getGmtCreateStart() != null &&
                empContactsQuery.getGmtCreateEnd() != null) {
            example.and().andBetween("gmtCreate", empContactsQuery.getGmtCreateStart(),
                    empContactsQuery.getGmtCreateEnd());
        }
        if (empContactsQuery.getCreateUserId() != null) {
            example.and().andLike("createUserId", "%" + empContactsQuery.getCreateUserId() + "%");
        }
        if (empContactsQuery.getGmtModifiedStart() != null &&
                empContactsQuery.getGmtModifiedEnd() != null) {
            example.and().andBetween("gmtModified", empContactsQuery.getGmtModifiedStart(),
                    empContactsQuery.getGmtModifiedEnd());
        }
        if (empContactsQuery.getModifiedUserId() != null) {
            example.and().andLike("modifiedUserId", "%" + empContactsQuery.getModifiedUserId() + "%");
        }
        // 排序
        ExampleKit.setExampleOrder(example,empContactsQuery.getOrders());
        return example;
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public Integer deleteEmpContacts(TokenUser tokenUser, String empContactsId){
        return empContactsDAO.deleteByPrimaryKey(empContactsId);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public void deleteByCompanyId(String companyId, TokenUser tokenUser) {
        Example example = new Example(EmpContactsDO.class);
        example.and()
                .andEqualTo("companyId", companyId)
                .andEqualTo("valid", true)
                .andEqualTo("siteId", tokenUser.getSiteId());
        // 逻辑删除
        List<EmpContactsDO> list = empContactsDAO.selectByExample(example);
        String[] ids = list.stream()
                .map(BaseDO::getId).toArray(String[]::new);
        deleteByIds(tokenUser, ids);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public void publishEmpContactsList(List<EmpContactsDTO> empContactsList, String companyId, String empId, TokenUser tokenUser) {
        // 删除某个员工所有的
        deleteByEmpId(empId, tokenUser);

        if (CollectionUtils.isEmpty(empContactsList)) {
            return;
        }

        empContactsList.forEach(
                empContactsDTO -> {
                    empContactsDTO.setCompanyId(companyId);
                    empContactsDTO.setEmpId(empId);
                    // 新增
                    EmpContactsAddDTO empContactsAddDTO = empContactsDTO.to(EmpContactsAddDTO.class);
                    save(empContactsAddDTO, tokenUser);
                }
        );
    }

    @Override
    public List<EmpContactsDO> listByEmpId(String empId, String siteId) {
        Example example = new Example(EmpContactsDO.class);
        example.and()
                .andEqualTo("empId", empId)
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        // example.selectProperties("name","phone","relation","address");
        example.orderBy("gmtCreate");
        return empContactsDAO.selectByExample(example);
    }

    @Override
    public List<EmpContactsDO> listByEmpIdList(List<String> empIdList, TokenUser tokenUser) {
        if (CollectionUtils.isEmpty(empIdList)) {
            return new ArrayList<>();
        }
        Example example = new Example(EmpContactsDO.class);
        example.and()
                .andIn("empId", empIdList)
                .andEqualTo("valid", true)
                .andEqualTo("siteId", tokenUser.getSiteId());
        example.orderBy("gmtCreate");
        return empContactsDAO.selectByExample(example);
    }

    /**
     * 删除某个员工所有的
     *
     * @param empId     员工id
     * @param tokenUser 当前用户
     */
    private void deleteByEmpId(String empId, TokenUser tokenUser) {

        // 逻辑删除
        List<EmpContactsDO> list = listByEmpId(empId, tokenUser.getSiteId());
        String[] ids = list.stream()
                .map(BaseDO::getId).toArray(String[]::new);
        deleteByIds(tokenUser, ids);
    }
}




